package toutiao

import (
	"crawl_toutiao/utils"
	"github.com/astaxie/beego/orm"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

type UrlInfo struct {
	Id          int64  `orm:"pk;auto"`
	Url         string `orm:"unique"`
	UrlMd5      string
	Keyword     *Keyword   `orm:"rel(fk)"` //设置一对多关系
	Picture     []*Picture `orm:"reverse(many)"`
	Title       string
	Category    string
	PublishTime time.Time `orm:"type(datetime)"`
	Updatetime  time.Time `orm:"type(datetime)"`
	Date        time.Time `orm:"auto_now_add;type(date)"`
	Addtime     time.Time `orm:"auto_now_add;type(datetime)"`
}

type Url struct {
	Id      int64    `orm:"pk;auto"`
	Keyword *Keyword `orm:"rel(fk)"`
	Url     string   `orm:"unique"`
	UrlMd5  string
	Addtime time.Time `orm:"auto_now_add;type(datetime)"`
}

func AddUrls(u string, id int64) {
	o := orm.NewOrm()
	keyword := &Keyword{Id: id}
	o.Read(keyword, "Id")

	imgUrl := &Url{
		Url:     u,
		Keyword: keyword,
		UrlMd5:  utils.EncodeMd5(u),
		Addtime: time.Now(),
	}

	if created, _, err := o.ReadOrCreate(imgUrl, "Url"); err == nil {
		if created {
			go DailyNumIncrement(keyword)
		}
	}
}

func GetUrlsAll() (u []Url) {
	o := orm.NewOrm()
	_, err := o.QueryTable("url").Limit(-1).All(&u)
	if err != nil {
		log.Println(err)
	}
	return
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func DirExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			os.Mkdir(path, 0777)
			return true, nil
		}
	}

	return true, nil
}

func SaveImage(url, path string) {
	res, err := http.Get(url)
	defer res.Body.Close()

	if err != nil {
		log.Printf("HTTP ERROR:%s", err)
		return
	}

	//根据URL文件名创建文件
	filename := filepath.Base(url)
	file, err := os.Create(path + "/" + filename + ".jpg")
	if err != nil {
		log.Printf("HTTP ERROR:%s", err)
		return
	}

	// 写入文件
	io.Copy(file, res.Body)
	log.Printf(">>>下载图片:(%s)===>>>", filename+".jpg")
}
